<template>
    <div>
        <!-- <button @click="printQRCode">测试打印机</button>
        <button @click="close">结束打印</button>
        <button @click="updatePrinterList">获取打印机信息</button>
        <button @click="onPrintRawData">打印机打印信息</button>
        <button @click="test">测试打印信息</button>
        <button @click="onPrintImageData">打印BASE64</button> -->
        <div ref="preview-list" class="table" :key="tableKey">
            <!-- <img :src="imgUrl"> -->
            <table border="0">
                <tr style="height: 66px;">
                    <th colspan="3">
                        <img src="@/assets/images/logo.png" alt="" class="title-img">
                        房喜
                    </th>
                </tr>
                <tr style="height: 45px;">
                    <td colspan="3" style="text-align: center;">{{ orderLists.orderType == 1 ? '采购订单' :
                        orderLists.orderType == 2 ? '线上订单' : '零售订单' }}</td>
                </tr>
                <tr>
                    <td style="width: 50%;">商品列表</td>
                    <td colspan="2"></td>
                </tr>
                <tbody v-for="(item, index) in orderLists.fxOrderItemList" :key="item.id">
                    <tr>
                        <!-- <td colspan="2"><span>1.</span>商品名称:<span>妮维雅洁面洗面奶护肤商品（畅销品）</span></td> -->
                        <td colspan="4"><span>{{ index + 1 }}.</span>商品名称:<span>{{ item.goodName }}</span></td>
                    </tr>
                    <tr>
                        <td style="text-align: right;">数量:<span>{{ item.goodCount }}</span></td>
                        <td style="text-align: right;">单价:<span>{{ item.goodPrice }}</span> </td>
                    </tr>
                </tbody>
                <tr v-if="orderLists.orderType == 2">
                    <td colspan="3" style="text-align: right;">配送费：{{ orderLists.deliveryCost || 0 }}（元）</td>
                </tr>
                <tr>
                    <td colspan="3" style="text-align: right;">总计：{{ orderLists.payMoney }}（元）</td>
                </tr>
                <tr v-if="orderLists.orderType !== 3">
                    <td colspan="3">收货信息：{{ orderLists.userName }}，{{ orderLists.phoneNumber }}</td>
                </tr>
                <tr v-if="orderLists.orderType !== 3">
                    <td colspan="3">收货地址：{{ orderLists.receiveAddress }}</td>
                </tr>
                <tr v-if="orderLists.orderType !== 3">
                    <td colspan="3">{{ orderLists.orderType == 1 ? '配送供应商名称' : '配送商家' }}：{{ orderLists.storeName }}</td>
                </tr>
                <tr v-if="orderLists.orderType !== 3">
                    <td colspan="3">配送人电话：{{ orderLists.storePhone }}</td>
                </tr>
                <tr>
                    <td colspan="3">下单时间：{{ orderLists.createTime }}</td>
                </tr>
            </table>
        </div>
    </div>
</template>
<script>
import { DTPWeb } from "dtpweb";
import html2canvas from 'html2canvas'
import { getOrderList } from "../../api/printe";
import dayjs from 'dayjs';
export default {
    name: 'PrinterOrder',
    components: {

    },
    props: {
        orderLists: {
            type: Object,
            default: {},
        }
    },
    data() {
        return {
            printers: [{ name: "未检测到打印机", value: {} }],
            currPrinter: { name: "" },
            printData: [],
            imgUrl: '',
            currOrientation: 0,
            api: null,
            orderList: {},
            tableKey: true,
        }
    },
    computed: {

    },
    watch: {
        orderLists(val, oldval) {
            this.getDocument()
        }
    },
    mounted() {
        this.api = DTPWeb.getInstance()
        // this.detectionPrinter()
        this.updatePrinterList()
        // setInterval(() => {
        //     this.getUserOrderList()
        // }, 30 * 1000)
    },
    methods: {
        getUserOrderList() {
            const startTime = dayjs().subtract(30, 'second').format('YYYY-MM-DD hh:mm:ss')
            const endTime = dayjs().format('YYYY-MM-DD hh:mm:ss')
            getOrderList({ startTime, endTime }).then(res => {
                if (res.code == 200) {
                    if (res.data.length > 0) {

                    }
                    for (let i = 0; i < res.data.length; i++) {
                        this.orderList = res.data[i];
                    }
                }
            })
        },
        // 获取元素
        getDocument() {
            this.$nextTick(() => {
                const element = this.$refs['preview-list'];
                console.log(element, 'element');

                html2canvas(element).then(canvas => {
                    const dataUrl = canvas.toDataURL();
                    this.imgUrl = dataUrl
                    if (!this.api) return
                    this.api.openPrinter()
                    this.startPrinte(dataUrl)
                    // this.api.closePrinter();
                });
            })
        },
        // 检测打印机
        detectionPrinter() {
            DTPWeb.checkServer({
                callback: (api, server) => {
                    this.api = api
                    if (!api) {
                        alert('来订单了，但未检测到打印机！')
                    }
                }
            })
        },
        // 开始打印
        startPrinte(data) {
            this.api.setParam({ id: 1, value: 0 })
            this.api.printImage({
                data,
                printerName: this.currPrinter?.name,
                copies: 1,
                orientation: this.currOrientation,
            });
            this.api.commitJob(() => {
                // 打印完毕后关闭打印机
                this.api.closePrinter();
            });

        },
        /**
         * 直接打印BASE64图片测试
         */
        onPrintImageData() {
            /**
             * @type {HTMLElement}
             */
            const datas = this.$refs["preview-list"];

            if (datas && datas.childNodes) {
                const childNodes = datas.childNodes;
                console.log(childNodes[0].src, 888888888);
                for (let i = 0; i < childNodes.length; i++) {
                    if (childNodes[i].src) {
                        this.api.printImage({
                            data: childNodes[i].src,
                            printerName: this.currPrinter?.name,
                            copies: 2,
                            orientation: this.currOrientation,
                        });
                    }
                }
            }
        },
        printRawData(rawData, callback) {
            const printer = this.currPrinter || {};
            return this.api.printRawData({
                // 打印数据，支持 Uint8Array，base64字符串，16进制字符串等格式的数据。
                data: rawData,
                // 打印机名称
                printerName: printer.name,
                // 打印份数
                // copies: 1,
                // 打印任务名称
                // jobName: "",
                callback: (res) => {
                    callback && callback(res);
                },
            });
        },
        onPrintRawData() {
            if (!this.printData || this.printData.length <= 0) {
                console.warn(`---- 未检测到打印数据！`);
                return;
            }
            const pageList = this.printData.map((v) => v.join(""));
            this.printRawList(pageList, 0);
        },
        /**
         * 循环打印所有打印数据。
         * @param {string[]} dataList 打印数据列表。
         * @param {number} index 当前打印页索引。
         */
        printRawList(dataList, index) {
            index = index || 0;
            if (!dataList || dataList.length <= 0) {
                console.log("未检测到打印数据！");
                return;
            }
            //
            var printData = dataList[index];
            if (!printData) {
                console.log("---- 无效的打印数据！");
                return;
            }
            //
            console.log(`----- 准备打印第 [${index + 1}] 条数据:`);
            this.printRawData(printData, (res) => {
                if (res) {
                    console.log(`---- 第 [${index + 1}] 条数据打印成功！`);
                } else {
                    console.log(`---- 第 [${index + 1}] 条数据打印失败！`);
                }
                //
                if (++index < dataList.length) {
                    // 打印下一张标签
                    this.printRawList(dataList, index);
                } else {
                    console.log("---- 所有标签全部打印完毕！");
                }
            });
        },
        // 获取打印机信息
        updatePrinterList() {
            if (!this.api) return;
            //
            const api = this.api;
            //
            api.getPrinters((values) => {
                // 清空旧打印机列表
                this.printers.splice(0);
                //
                if (values?.length > 0) {
                    for (const item of values) {
                        const title = api.isLocalPrinter(item)
                            ? item.deviceName || item.name
                            : `${item.deviceName || item.name}@${item.ip}`;
                        this.printers.push({
                            name: title,
                            value: item,
                        });
                    }
                } else {
                    this.printers.push({ name: "未检测到打印机", value: "" });
                }
                //
                this.currPrinter = this.printers[0].value;
            });
        },
        // 打印机打印信息
        // printQRCode() {
        //     const labelWidth = 30;
        //     const labelHeight = 30;
        //     const margin = 5;
        //     const qrcodeWidth = labelWidth - margin * 2;
        //     const printerName = this.currPrinter.name;
        //     // 判断接口是否可用
        //     if (!this.api) return;
        //     // 1. 链接目标打印机
        //     this.api.openPrinter(printerName, (success) => {

        //         if (success) {
        //             // 2. 创建一个指定大小的标签任务
        //             this.api.startJob({});
        //             // 3. 在打印任务上绘制二维码
        //             this.api.draw2DQRCode({ x: margin, y: margin, width: qrcodeWidth });
        //             // 4. 结束打印任务的绘制，开始打印
        //             this.api.commitJob((res) => {
        //                 // 如果当前任务类型为预览类型，则显示预览效果
        //                 this.previewJobs(res);
        //                 // 打印完毕后关闭打印机
        //             });
        //         }
        //     });
        // },
        /**
         * 获取当前任务的图片信息；
         */
        // previewJobs(res) {
        //     if (!res) return;
        //     // 先清空预览区域；
        //     this.$refs["preview-list"].innerHTML = "";
        //     //
        //     if (res.printData) {
        //         this.printData = res.printData;
        //         console.log(`---- printData:`);
        //         console.log(res.printData);
        //     }
        //     if (res.previewData) {
        //         this.previewPages(res.previewData);
        //     }
        // },
        close() {
            this.api.closePrinter();

        }
    }
};
</script>
<style lange='sass' scoped>
.table {
    width: 400px;
    height: 100%;
    font-size: 20px;
}

table {
    border-collapse: collapse;
    width: 100%;

    th,
    td {
        border: none;
        padding: 8px;
    }

    th {
        font-size: 28px;
    }

    .title-img {
        width: 30px;
        height: 30px;
        display: inline-block;
        vertical-align: middle;
        margin-top: -5px;
        margin-right: 8px;
    }
}


.flex {
    display: flex;
    justify-content: center;
    align-items: center;
}

.invisible-element {
    position: absolute;
    top: -9999px;
    left: -9999px;
    opacity: 0;
    pointer-events: none;
}
</style>